package com.farm.wcp.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.farm.authority.FarmAuthorityService;
import com.farm.authority.service.UserServiceInter;
import com.farm.core.auth.domain.LoginUser;
import com.farm.core.page.ViewMode;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.query.DataQuerys;
import com.farm.core.sql.result.DataResult;
import com.farm.core.time.TimeTool;
import com.farm.project.domain.Company;
import com.farm.project.domain.Field;
import com.farm.project.domain.Project;
import com.farm.project.domain.ProjectFieldins;
import com.farm.project.domain.ProjectGradation;
import com.farm.project.domain.ProjectType;
import com.farm.project.domain.Task;
import com.farm.project.domain.TaskFile;
import com.farm.project.domain.TaskLog;
import com.farm.project.service.CompanyServiceInter;
import com.farm.project.service.ProjectFieldinsServiceInter;
import com.farm.project.service.ProjectGradationServiceInter;
import com.farm.project.service.ProjectServiceInter;
import com.farm.project.service.ProjectTypeServiceInter;
import com.farm.project.service.TaskServiceInter;
import com.farm.project.service.TaskTypeServiceInter;
import com.farm.project.service.TaskuserServiceInter;
import com.farm.wcp.util.ThemesUtil;
import com.farm.web.WebUtils;

/**
 * 工作视图
 * 
 * @author autoCode
 * 
 */
@RequestMapping("/projectView")
@Controller
public class ProjectViewWebController extends WebUtils {
	private static final Logger log = Logger.getLogger(ProjectViewWebController.class);
	@Resource
	private ProjectServiceInter projectServiceImpl;
	@Resource
	private ProjectTypeServiceInter projectTypeServiceImpl;
	@Resource
	private ProjectGradationServiceInter projectGradationServiceImpl;
	@Resource
	private TaskServiceInter taskServiceImpl;
	@Resource
	private TaskTypeServiceInter taskTypeServiceImpl;
	@Resource
	private ProjectFieldinsServiceInter projectFieldinsServiceImpl;
	@Resource
	private UserServiceInter userServiceImpl;
	@Resource
	private CompanyServiceInter companyServiceImpl;
	@Resource
	private TaskuserServiceInter taskUserServiceImpl;

	/***
	 * 选择查询周期
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/chooseRound")
	public ModelAndView userRound(String objType, String baseDate, HttpServletRequest request, HttpSession session) {
		ViewMode view = ViewMode.getInstance();
		try {
			view.putAttr("objType", objType);
			view.putAttr("baseDate", baseDate);
			return view.returnModelAndView("/web-simple/projectview/dataRound");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePage("error-sys"));
		}
	}

	/***
	 * 周报对象列表（人员|项目）(选完周期后进入该界面)
	 * 
	 * @param objType   对象类型(user|project)
	 * @param baseDate  基准日期
	 * @param roundUnit 周期类型（WEEK|MONTH|DAY）
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/chooseObj")
	public ModelAndView chooseObj(String objType, String baseDate, String roundUnit, HttpServletRequest request,
			HttpSession session) {
		ViewMode view = ViewMode.getInstance();
		try {
			String[] roundDate = getRoundDate(roundUnit, baseDate, view);
			view.putAttr("stime", TimeTool.getFormatTimeDate12(roundDate[0], "yyyy-MM-dd"));
			view.putAttr("etime", TimeTool.getFormatTimeDate12(roundDate[1], "yyyy-MM-dd"));
			view.putAttr("baseDate", TimeTool.parseDate(baseDate, "yyyy-MM-dd").getTime());
			view.putAttr("objType", objType);
			view.putAttr("roundUnit", roundUnit);
			if (objType.equals("user")) {
				// 人员周报
				List<String> userids = new ArrayList<>();
				userids.add(getCurrentUser(session).getId());
				List<Map<String, Object>> users = projectServiceImpl.getUserTaskNums(userids, roundDate[0],
						roundDate[1]);
				view.putAttr("users", users);
			} else {
				// 项目周报
				List<Project> projects = new ArrayList<>();
				projects = projectServiceImpl.getliveProjects(getCurrentUser(session), roundDate[0], roundDate[1]);
				view.putAttr("projects", projects);
			}
			return view.returnModelAndView("/web-simple/projectview/roundObjList");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePage("error-sys"));
		}
	}

	/**
	 * 根据周期类型，填充周期时间
	 * 
	 * @param roundUnit 周期类型（WEEK|MONTH|DAY）
	 * @param baseDate  基准日期，会根据该日期计算相关周或者月范围
	 * @param view
	 * @throws ParseException
	 */
	private String[] getRoundDate(String roundUnit, String baseDate, ViewMode view) throws ParseException {
		// 計算統計周期的開始時間和結束時間
		String stime = null;
		String etime = null;
		if ("WEEK".equals(roundUnit)) {
			Date date = TimeTool.parseDate(baseDate, "yyyy-MM-dd");
			stime = TimeTool.getFirstDayOfWeek(Integer.valueOf(getYear(baseDate)), TimeTool.getWeekOfYearNum(date))
					.replaceAll("-", "");
			etime = TimeTool.getLastDayOfWeek(Integer.valueOf(getYear(baseDate)), TimeTool.getWeekOfYearNum(date))
					.replaceAll("-", "");
		} else if ("MONTH".equals(roundUnit)) {
			stime = TimeTool.getFisrtDayOfMonth(Integer.valueOf(getYear(baseDate)), Integer.valueOf(getMonth(baseDate)))
					.replaceAll("-", "");
			etime = TimeTool.getLastDayOfMonth(Integer.valueOf(getYear(baseDate)), Integer.valueOf(getMonth(baseDate)))
					.replaceAll("-", "");
		} else {// DAY
			stime = formatDate(baseDate);
			etime = formatDate(baseDate);
		}
		return new String[] { stime, etime };
	}

	/**
	 * 格式化日期字符串
	 * 
	 * @param dataStr yyyy-mm-dd
	 * @return
	 */
	private String formatDate(String dataStr) {
		String[] dateSpli = dataStr.split("-");
		return dateSpli[0] + (dateSpli[1].length() > 1 ? dateSpli[1] : "0" + dateSpli[1])
				+ (dateSpli[2].length() > 1 ? dateSpli[2] : "0" + dateSpli[2]);
	}

	private String getYear(String dataStr) {
		String[] dateSpli = dataStr.split("-");
		return dateSpli[0];
	}

	private String getMonth(String dataStr) {
		String[] dateSpli = dataStr.split("-");
		return dateSpli[1];
	}

	private String getDay(String dataStr) {
		String[] dateSpli = dataStr.split("-");
		return dateSpli[2];
	}

	/**
	 * 处理自定义属性查询
	 * 
	 * @param query
	 * @param fieldLimits
	 * @return
	 */
	private DataQuery initFieldLimits(DataQuery query, String fieldLimits) {
		if (StringUtils.isNotBlank(fieldLimits)) {
			String[] rules = fieldLimits.split("%,");
			for (String rule : rules) {
				String[] rulearray = rule.split("%:");
				if (rulearray.length == 2) {
					query.addSqlRule(
							" and a.ID in (select PROJECTID from PLOGS_PROJECT_FIELDINS where uuid='" + rulearray[0]
									+ "' and (val='" + rulearray[1] + "' or valtitle like'%" + rulearray[1] + "%' ))");
				}
			}
		}
		return query;
	}

	/***
	 * 项目视图首页
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView index(String name, String state, String fieldUuid, String sortType, Integer page,
			String fieldLimits, HttpServletRequest request, HttpSession session) {
		ViewMode view = ViewMode.getInstance();
		view.putAttr("fieldLimits", fieldLimits);
		DataQuery dbQuery = new DataQuery();
		try {
			// 处理自定义属性查询
			dbQuery = initFieldLimits(dbQuery, fieldLimits);

			if (StringUtils.isBlank(state)) {
				// 查询全部项目
				// dbQuery.addSqlRule("and a.state !='2'");
			} else {
				dbQuery.addSqlRule("and a.state ='" + state + "'");
			}
			// name有可能是项目类型的ID
			ProjectType projectType = projectTypeServiceImpl.getProjecttypeEntity(name);
			if (projectType != null && projectType.getModel().equals("1")) {
				{// 处理分类类型的自定义属性
					List<Field> fields = projectTypeServiceImpl.getDataSearchFields(projectType.getId());
					for (Field field : fields) {
						// 解析控件枚举字段，用于前台查询
						if (StringUtils.isNotBlank(field.getEnums())) {
							List<String> enums = parseIds(field.getEnums());
							List<String[]> enumsArray = new ArrayList<String[]>();
							for (String node : enums) {
								String[] array = node.split(":");
								if (array.length == 2) {
									enumsArray.add(array);
								}
							}
							field.setEnumlist(enumsArray);
						}
					}
					view.putAttr("fields", fields);
				}
				// 查询项目分类
				dbQuery.addSqlRule("and TYPEID ='" + name + "'");
			} else {
				// 查询项目ID或名称
				if (StringUtils.isNotBlank(name) && projectType == null) {
					DataQuerys.wipeVirus(name);
					dbQuery.addSqlRule("and (a.id like '%" + name + "%' or a.name like '%" + name
							+ "%' or c2.name like '%" + name + "%')");
				}
			}
			List<ProjectType> types = projectTypeServiceImpl.getAllTypes("1");
			DBSort sort = null;
			if (StringUtils.isNotBlank(fieldUuid)) {
				sort = new DBSort(fieldUuid, "ASC".equals(sortType) ? "ASC" : "DESC");
			}
			DataResult projects = projectServiceImpl.getProjectsForView(dbQuery, sort, page, 10,
					getCurrentUser(session));
			view.putAttr("projects", projects);
			view.putAttr("MODEL", "PROJECTVIEW");
			view.putAttr("types", types);
			view.putAttr("state", state);
			view.putAttr("name", name);
			view.putAttr("fieldUuid", fieldUuid);
			view.putAttr("sortType", sortType);
			return view.returnModelAndView("/web-simple/projectview/index");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePage("error-sys"));
		}
	}

	/***
	 * 项目信息查看
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/projectInfo")
	public ModelAndView project(String projectId, String stime, String etime, HttpServletRequest request,
			HttpSession session) {
		ViewMode view = ViewMode.getInstance();
		try {
			List<ProjectFieldins> fields = projectFieldinsServiceImpl.getProjectFields(projectId);
			Project project = projectServiceImpl.getProjectEntity(projectId);
			// 項目任務
			List<Task> tasks = null;
			List<Map<String, Object>> files = null;
			if (StringUtils.isNotBlank(stime) && StringUtils.isNotBlank(etime)) {
				// 項目任務
				tasks = projectServiceImpl.getProjectTasks(projectId, stime, etime, null);
				// 任務下的附件
				files = projectServiceImpl.getProjectTaskFiles(projectId, stime, etime, null);
			} else {
				// 項目任務
				tasks = projectServiceImpl.getProjectTasks(projectId);
				// 任務下的附件
				files = projectServiceImpl.getProjectTaskFiles(projectId);
				view.putAttr("MODEL", "PROJECTVIEW");
			}
			view.putAttr("tasks", tasks);
			view.putAttr("files", files);
			// 项目的任务类型
			List<Map<String, Object>> tasktypes = projectServiceImpl.filterTaskTypesByTasks(tasks,
					projectServiceImpl.getProjectTaskTypes(projectId));
			// 項目階段
			List<ProjectGradation> gradations = projectServiceImpl.filterGradationByTasks(tasks,
					projectServiceImpl.getProjectHasGradation(projectId));
			LoginUser cuser = FarmAuthorityService.getInstance().getUserById(project.getCuser());
			ProjectType projectType = projectTypeServiceImpl.getProjecttypeEntity(project.getTypeid());
			Company company = companyServiceImpl.getProjectCompany(project.getId());
			if (company != null) {
				List<Project> projects = projectServiceImpl.getCompanyProjects(company.getId());
				view.putAttr("projects", projects);
			}
			view.putAttr("company", company);
			view.putAttr("tasktypes", tasktypes);
			view.putAttr("gradations", gradations);
			view.putAttr("cuser", cuser);
			view.putAttr("projectType", projectType);
			view.putAttr("fields", fields);
			view.putAttr("project", project);
			view.putAttr("stime", stime);
			view.putAttr("etime", etime);
			return view.returnModelAndView("/web-simple/projectview/projectRoundInfo");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePage("error-sys"));
		}
	}

	/***
	 * 人员任务查看（周报）
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/personInfo")
	public ModelAndView personInfo(String userId, String stime, String etime, HttpServletRequest request,
			HttpSession session) {
		ViewMode view = ViewMode.getInstance();
		try {
			LoginUser user = FarmAuthorityService.getInstance().getUserById(userId);
			view.putAttr("user", user);
			view.putAttr("org", userServiceImpl.getOrg(userId));
			// 項目任務
			List<Task> tasks = null;
			List<Map<String, Object>> files = null;
			// 項目任務
			tasks = projectServiceImpl.getProjectTasks(null, stime, etime, user);
			// 任務下的附件
			files = projectServiceImpl.getProjectTaskFiles(null, stime, etime, user);
			view.putAttr("tasks", tasks);
			view.putAttr("files", files);
			view.putAttr("projects", getProjectInfos(tasks));
			view.putAttr("stime", stime);
			view.putAttr("etime", etime);
			return view.returnModelAndView("/web-simple/projectview/personRoundInfo");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePage("error-sys"));
		}
	}

	private Map<String, String> getProjectInfos(List<Task> tasks) {
		Map<String, String> projects = new HashMap<>();
		for (Task task : tasks) {
			projects.put(task.getProjectid(), task.getPcontent());
		}
		return projects;
	}

	/***
	 * 任务信息
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/taskinfo")
	public ModelAndView taskinfo(String taskid, HttpServletRequest request, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();

			{
				// 处理关系人
				List<Map<String, Object>> taskusers = taskUserServiceImpl.getTaskUsers(taskid);
				List<Map<String, Object>> doUsers = new ArrayList<>();
				List<Map<String, Object>> managerUsers = new ArrayList<>();
				for (Map<String, Object> user : taskusers) {
					String poptype = (String) user.get("POPTYPE");
					if (poptype.equals("1")) {
						managerUsers.add(user);
					}
					if (poptype.equals("2")) {
						doUsers.add(user);
					}
				}
				view.putAttr("doUsers", doUsers.size() > 0 ? doUsers : managerUsers);
				view.putAttr("managerUsers", managerUsers);
				view.putAttr("isDoUser", taskUserServiceImpl.isDoUser(taskid, getCurrentUser(session)));
				view.putAttr("isManagerUser", taskUserServiceImpl.isManagerUser(taskid, getCurrentUser(session)));
			}

			Task task = taskServiceImpl.getTaskEntity(taskid);
			view.putAttr("task", task);
			// 获得任务项目名称
			Project project = projectServiceImpl.getProjectEntity(task.getProjectid());
			view.putAttr("project", project);
			if (StringUtils.isNotBlank(task.getReadfileid())) {
				String text = taskServiceImpl.readText(task.getReadfileid());
				view.putAttr("text", text);
			}
			List<TaskLog> logs = taskServiceImpl.getLogs(taskid);
			List<TaskFile> files = taskServiceImpl.getTaskfiles(taskid);
			Company company = companyServiceImpl.getProjectCompany(project.getId());
			view.putAttr("company", company);
			view.putAttr("files", files);
			view.putAttr("logs", logs);
			view.putAttr("user", FarmAuthorityService.getInstance().getUserById(task.getUserid()));
			return view.returnModelAndView("/web-simple/projectview/taskinfo");
		} catch (Exception e) {
			log.error(e);
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePage("error-sys"));
		}
	}
}